<script setup lang="ts">
import { ref, watch } from 'vue'
import { useUserStore } from '@/stores/user'
import { ElNotification, ElMessage } from 'element-plus'
import type { UploadProps } from 'element-plus'
import http from '@/http'
import { Plus } from '@element-plus/icons-vue'

const userStore = useUserStore()

// 使用一个本地的 ref 来编辑表单，避免在用户点击“保存”前直接修改全局状态
const profileForm = ref({
  avatarUrl: '',
  intro: '',
})

// 监听抽屉的打开/关闭状态
watch(
  () => userStore.profileDrawerVisible,
  (isVisible) => {
    // 当抽屉打开时，用 store 中的最新数据来填充表单
    if (isVisible) {
      profileForm.value.avatarUrl = userStore.avatarUrl || ''
      profileForm.value.intro = userStore.intro || ''
    }
  },
)

// --- 上传相关逻辑 ---
const uploadActionUrl = `${import.meta.env.VITE_API_BASE_URL}/api/files/upload`

// 头像上传前的校验
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  const isLt2M = rawFile.size / 1024 / 1024 < 2
  if (!isLt2M) {
    ElMessage.error('头像图片大小不能超过 2MB!')
  }
  return isLt2M
}

// 头像上传成功时的回调
const handleAvatarSuccess: UploadProps['onSuccess'] = (response) => {
  // response 就是后端返回的图片 URL
  profileForm.value.avatarUrl = response
  ElNotification.success('头像上传成功！')
}

// --- 保存修改的逻辑 ---
const saveProfile = async () => {
  try {
    // 将本地表单的数据提交到后端
    await http.put('/api/users/me', profileForm.value)
    ElNotification.success('个人信息更新成功！')

    // 更新成功后，做两件事：
    // 1. 重新获取最新的用户信息，以更新整个应用的显示
    await userStore.fetchUserInfo()
    // 2. 关闭抽屉
    userStore.closeProfileDrawer()
  } catch (error) {
    console.error('更新个人信息失败:', error)
    ElNotification.error('更新失败，请重试')
  }
}
</script>

<template>
  <el-drawer
    :model-value="userStore.profileDrawerVisible"
    title="修改个人信息"
    direction="rtl"
    @close="userStore.closeProfileDrawer"
  >
    <el-form :model="profileForm" label-position="top">
      <el-form-item label="头像">
        <el-upload
          class="avatar-uploader"
          :action="uploadActionUrl"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
          :headers="{ Authorization: `Bearer ${userStore.token}` }"
        >
          <img v-if="profileForm.avatarUrl" :src="profileForm.avatarUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>

      <el-form-item label="个人简介">
        <el-input
          v-model="profileForm.intro"
          type="textarea"
          :rows="5"
          placeholder="介绍一下自己吧"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="saveProfile">保存修改</el-button>
        <el-button @click="userStore.closeProfileDrawer">取消</el-button>
      </el-form-item>
    </el-form>
  </el-drawer>
</template>

<style>
/* 这些样式可以放在全局 CSS 中，也可以放在这里 */
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}
.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}
.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
